"""This package contains modules related to objective functions, optimizations, and network architectures.

To add a custom controller class called 'dummy', you need to add a file called 'dummy_controller.py' and define a subclass Dummycontroller inherited from Basecontroller.
You need to implement the following five functions:
    -- <__init__>:                      initialize the class; first call Basecontroller.__init__(self, opt).
    -- <set_input>:                     unpack data from dataset and apply preprocessing.
    -- <forward>:                       produce intermediate results.
    -- <optimize_parameters>:           calculate loss, gradients, and update network weights.
    -- <modify_commandline_options>:    (optionally) add controller-specific options and set default options.

In the function <__init__>, you need to define four lists:
    -- self.loss_names (str list):          specify the training losses that you want to plot and save.
    -- self.controller_names (str list):         define networks used in our training.
    -- self.visual_names (str list):        specify the images that you want to display and save.
    -- self.optimizers (optimizer list):    define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_controller.py for an usage.

Now you can use the controller class by specifying flag '--controller dummy'.
See our template controller class 'template_controller.py' for more details.
"""

import importlib
from controllers.base_controller import BaseController


def find_controller_using_name(controller_name):
    """Import the module "controllers/[controller_name]_controller.py".

    In the file, the class called DatasetNamecontroller() will
    be instantiated. It has to be a subclass of Basecontroller,
    and it is case-insensitive.
    """
    controller_filename = "controllers." + controller_name + "_controller"
    controllerlib = importlib.import_module(controller_filename)
    controller = None
    target_controller_name = controller_name.replace('_', '') + 'controller'
    for name, cls in controllerlib.__dict__.items():
        if name.lower() == target_controller_name.lower() \
           and issubclass(cls, BaseController):
            controller = cls

    if controller is None:
        print("In %s.py, there should be a subclass of Basecontroller with class name that matches %s in lowercase." % (controller_filename, target_controller_name))
        exit(0)

    return controller


def get_option_setter(controller_name):
    """Return the static method <modify_commandline_options> of the controller class."""
    controller_class = find_controller_using_name(controller_name)
    return controller_class.modify_commandline_options


def create_controller(opt):
    """Create a controller given the option.

    This function warps the class CustomDatasetDataLoader.
    This is the main interface between this package and 'train.py'/'test.py'

    Example:
        >>> from controllers import create_controller
        >>> controller = create_controller(opt)
    """
    controller = find_controller_using_name(opt.controller)
    instance = controller(opt)
    print("controller [%s] was created" % type(instance).__name__)
    return instance
